//render.js //渲染
const { ipcRenderer } = require('electron')

// LocalStorage相关函数
const STORAGE_KEY = 'lastLiveRoomUrl'

// 保存直播间网址到LocalStorage
function saveLastUrl(url) {
  try {
    localStorage.setItem(STORAGE_KEY, url)
  } catch (error) {
    console.error('保存网址失败:', error)
  }
}

// 从LocalStorage读取上次的直播间网址
function getLastUrl() {
  try {
    return localStorage.getItem(STORAGE_KEY) || ''
  } catch (error) {
    console.error('读取网址失败:', error)
    return ''
  }
}

// 页面加载完成后恢复上次的网址和平台信息
window.addEventListener('DOMContentLoaded', async () => {
  const inputElement = document.getElementById('input')
  const lastUrl = getLastUrl()
  if (lastUrl && inputElement) {
    inputElement.value = lastUrl
    inputElement.placeholder = '上次使用: ' + lastUrl
  }
  
  // 检查是否有当前连接的平台
  try {
    const result = await ipcRenderer.invoke('get-current-platform')
    if (result.success && result.platform && result.platform.name) {
      const platform = detectPlatform(result.platform.url)
      updateCurrentPlatform(result.platform.url, platform)
    }
  } catch (error) {
    console.error('获取当前平台信息失败:', error)
  }
})

// 平台检测函数
// 这里的name决定了main.js中显示的哪个平台
function detectPlatform(url) {
  const platforms = {
    'douyin.com': { name: '抖音', icon: '<i class="bi bi-music-note"></i>' },
    'tiktok.com': { name: 'TikTok', icon: '<i class="bi bi-tiktok"></i>' },
    'kuaishou.com': { name: '快手', icon: '<i class="bi bi-lightning"></i>' },
    'bilibili.com': { name: 'BiliBili', icon: '<i class="bi bi-play-btn"></i>' },
    'channels.weixin.qq.com': { name: '视频号', icon: '<i class="bi bi-camera-video"></i>' }
  }
  
  for (const [domain, info] of Object.entries(platforms)) {
    if (url.includes(domain)) {
      return info
    }
  }
  
  return { name: '未知平台', icon: '<i class="bi bi-question-circle"></i>' }
}

// 更新当前平台显示
function updateCurrentPlatform(url, platform) {
  const platformSection = document.getElementById('current-platform-section')
  const platformIcon = document.getElementById('current-platform-icon')
  const platformName = document.getElementById('current-platform-name')
  const platformUrl = document.getElementById('current-platform-url')
  
  if (url && platform) {
    platformIcon.innerHTML = platform.icon
    platformName.textContent = platform.name
    platformUrl.textContent = url
    platformSection.style.display = 'block'
  } else {
    platformSection.style.display = 'none'
  }
}

// 进入直播间按钮点击事件
document.getElementById('goLive').addEventListener('click', async () => {
  const inputElement = document.getElementById('input')
  let url = inputElement.value.trim()
  
  if (!url) {
    alert('请输入直播间网址')
    return
  }
  
  // 自动补全http协议
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://' + url
    // 更新输入框显示补全后的网址
    inputElement.value = url
  }
  
  // 检测平台
  const platform = detectPlatform(url)
  
  try {
    // 显示加载状态
    const button = document.getElementById('goLive')
    const originalText = button.innerHTML
    button.innerHTML = '<i class="bi bi-hourglass-split"></i> 正在打开...'
    button.disabled = true
    
    // 调用主进程的openLiveRoom函数
    const result = await ipcRenderer.invoke('open-live-room', url)
    
    if (result.success) {
       // 保存成功打开的网址到LocalStorage
       saveLastUrl(url)
       
       // 更新当前平台显示
       updateCurrentPlatform(url, platform)
       
       // 同步平台信息到主进程
       await ipcRenderer.invoke('update-current-platform', {
         name: platform.name,
         url: url
       })
       
       // 成功时显示提示
       button.innerHTML = '<i class="bi bi-check-circle"></i> 已打开'
       setTimeout(() => {
         button.innerHTML = originalText
         button.disabled = false
       }, 2000)
     } else {
      // 失败时显示错误信息
      alert(result.message || '打开直播间失败')
      button.innerHTML = originalText
      button.disabled = false
    }
  } catch (error) {
    console.error('调用openLiveRoom失败:', error)
    alert('打开直播间时发生错误，请重试')
    
    // 恢复按钮状态
    const button = document.getElementById('goLive')
    button.innerHTML = '<i class="bi bi-play-circle"></i> 进入直播间'
    button.disabled = false
  }
})

// 回车键快捷操作
document.getElementById('input').addEventListener('keypress', (event) => {
  if (event.key === 'Enter') {
    document.getElementById('goLive').click()
  }
})

// WebSocket连接状态管理
let wsStatusInterval = null

// 更新WebSocket连接数量显示
async function updateWebSocketStatus() {
  try {
    const result = await ipcRenderer.invoke('websocket-client-count')
    
    const statusIndicator = document.getElementById('ws-status-indicator')
    const statusText = document.getElementById('ws-status-text')
    const connectionCount = document.getElementById('ws-connection-count')
    
    if (result.success) {
      // 服务器在线
      statusIndicator.className = 'status-indicator online me-2'
      statusText.textContent = '服务正常运行'
      connectionCount.textContent = result.count
    } else {
      // 服务器离线或错误
      statusIndicator.className = 'status-indicator offline me-2'
      statusText.textContent = '服务异常'
      connectionCount.textContent = '0'
    }
  } catch (error) {
    console.error('获取WebSocket状态失败:', error)
    
    const statusIndicator = document.getElementById('ws-status-indicator')
    const statusText = document.getElementById('ws-status-text')
    const connectionCount = document.getElementById('ws-connection-count')
    
    statusIndicator.className = 'status-indicator offline me-2'
    statusText.textContent = '连接失败'
    connectionCount.textContent = '0'
  }
}

// 页面加载完成后启动WebSocket状态监控
window.addEventListener('DOMContentLoaded', () => {
  // 立即更新一次状态
  updateWebSocketStatus()
  
  // 每3秒更新一次WebSocket连接状态
  wsStatusInterval = setInterval(updateWebSocketStatus, 3000)
})

// 监听直播间关闭事件
ipcRenderer.on('live-room-closed', () => {
  // 隐藏当前平台显示区域
  updateCurrentPlatform(null, null)
})

// 页面卸载时清理定时器
window.addEventListener('beforeunload', () => {
  if (wsStatusInterval) {
    clearInterval(wsStatusInterval)
  }
})